package org.example.config3;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: GongXl
 * @Date: 2021/3/26 11:48
 * @Description:
 */
@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME="sub";
    private static final String CLAIM_KEY_CREATED="created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * @Author GongXl
     * @Description 根据用户信息生成token
     * @Date 2021/3/26 13:52
     * @Param [userDetails]
     * @return java.lang.String
     **/
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    /**
     * @Author GongXl
     * @Description 用户名生成token
     * @Date 2021/3/27 9:04
     * @Param [username]
     * @return java.lang.String
     **/
    public String generateTokenByUsername(String username){
        Map<String,Object> claims = new HashMap();
        claims.put(CLAIM_KEY_USERNAME,username);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    /**
     * @Author GongXl
     * @Description 荷载生成JWT TOKEN
     * @Date 2021/3/26 13:48
     * @Param [claims]
     * @return java.lang.String
     **/
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }
    private Date generateExpirationDate(){
        return new Date(System.currentTimeMillis()+expiration*1000);
    }
    /**
     * @Author GongXl
     * @Description 从token中获得登录用户名
     * @Date 2021/3/26 13:53
     * @Param [token]
     * @return java.lang.String
     **/
    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            username = null;
        }
        return username;
    }
    /**
     * @Author GongXl
     * @Description 从token中获得荷载
     * @Date 2021/3/26 13:59
     * @Param [token]
     * @return io.jsonwebtoken.Claims
     **/
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }
    /**
     * @Author GongXl
     * @Description 验证token是否有效
     * @Date 2021/3/26 14:08
     * @Param [token, userDetails]
     * @return boolean
     **/
    public boolean validateToken(String token,UserDetails userDetails){
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && isTokenExpired(token);
    }
    /**
     * @Author GongXl
     * @Description 判断token是否失效
     * @Date 2021/3/26 14:07
     * @Param [token]
     * @return boolean
     **/
    private boolean isTokenExpired(String token) {
        Date expireDate = getExpiredDateFromToken(token);
        return expireDate.before(new Date());
    }
    /**
     * @Author GongXl
     * @Description 从token中获取过期时间
     * @Date 2021/3/26 14:09
     * @Param [token]
     * @return java.util.Date
     **/
    private Date getExpiredDateFromToken(String token) {
        Claims claimsFromToken = getClaimsFromToken(token);
        Date expiration = claimsFromToken.getExpiration();
        return expiration;
    }
    /**
     * @Author GongXl
     * @Description 判断token是否可以刷新
     * @Date 2021/3/26 14:12
     * @Param [token]
     * @return boolean
     **/
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }
    /**
     * @Author GongXl
     * @Description 刷新token
     * @Date 2021/3/26 16:16
     * @Param [token]
     * @return java.lang.String
     **/
    public String refreshToken(String token){
        Claims claimsFromToken = getClaimsFromToken(token);
        claimsFromToken.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claimsFromToken);
    }
}